<template>
  <view class="chatList-page">
    <view class="chatList-page-content">
      <uni-nav-bar title="对话" :border="false" class="custom-nav-bar">
        <template #right>
          <image :src="navBarAddBtnIcon" class="nav-bar-add-btn-icon" @click="handleMore" />
        </template>
      </uni-nav-bar>

      <view class="search-container">
        <uni-search-bar v-model="searchValue" placeholder="请输入" size="mini" class="search-input" cancelButton="none" @clear="onSearch" @confirm="onSearch" :maxlength="100"></uni-search-bar>
        <text class="search-btn" @click="onSearch">搜索</text>
      </view>

      <scroll-view scroll-y class="chat-list-main" :show-scrollbar="true" @scrolltolower="loadMore">
        <uni-list :class="['custom-list', chatListData.length > 0 ? '' : 'custom-list-empty']" :border="false">
          <template v-if="chatListData.length">
            <uni-swipe-action>
              <uni-swipe-action-item v-for="(item, index) in chatListData" :key="item.id" :right-options="swipeOptions" @click="handleSwipeClick($event, item)">
                <uni-list-item :clickable="true" ellipsis="1" :title="item.chatTitle" @click="() => handleClick(item)">
                  <template v-slot:header>
                    <view class="custom-thumb">
                      <image :src="item.icon" mode="aspectFit" class="thumb-image" />
                    </view>
                  </template>
                </uni-list-item>
              </uni-swipe-action-item>
            </uni-swipe-action>
          </template>
          <template v-else>
            <view class="main-enter">
              <image mode="aspectFit" :src="enterFromIcon" class="enterFrom-img" @click="enterDebug('logo')" />
              <view class="button-text">暂无数据</view>
            </view>
          </template>
        </uni-list>
        <view class="load-more" v-if="loadingMore">
          <text>加载中...</text>
        </view>
        <view class="no-more" v-if="noMoreData && hasTriedLoadMore">
          <text>没有更多数据了</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { getChatListApi, delChatApi } from '@/api/chatList';
  import { useChatStore } from '@/store/chat';
  import { useShowLoading } from '@/hooks/useShowLoading';
  import blueIcon from '/static/chatList/blue-icon.png';
  import greenIcon from '/static/chatList/green-icon.png';
  import yellowIcon from '/static/chatList/yellow-icon.png';
  import pinkIcon from '/static/chatList/pink-icon.png';
  import lavenderIIcon from '/static/chatList/lavender-icon.png';
  import purpleIcon from '/static/chatList/purple-icon.png';
  import { onShow } from '@dcloudio/uni-app';
  import navBarAddBtnIcon from '@/static/chat/nav-bar-add-btn-icon.png';
  import enterFromIcon from '@/static/agent/empty-icon.png';

  const chatStore = useChatStore();
  const { handleLoading, cancelLoading } = useShowLoading();

  const searchValue = ref('');
  const chatIconList = [blueIcon, greenIcon, yellowIcon, pinkIcon, lavenderIIcon, purpleIcon];
  const chatListData = ref([]);

  const loadingMore = ref(false);
  const noMoreData = ref(false);
  const hasTriedLoadMore = ref(false); 

  const onSearch = () => {
    pageInfo.value.pageNum = 1;
    noMoreData.value = false;
    hasTriedLoadMore.value = false; 
    getChatList();
  };

  const pageInfo = ref({
    pageNum: 1,
    pageSize: 20,
    total: 0
  });

  const getChatList = (showLoading = true) => {
    const apiData = {
      agentId: chatStore.agentId,
      keyword: searchValue.value,
      pageNum: pageInfo.value.pageNum,
      pageSize: pageInfo.value.pageSize
    };
    showLoading && handleLoading();
    getChatListApi(apiData)
      .then(res => {
        const resDataList = Array.isArray(res?.rows) ? res?.rows : [];

        if (pageInfo.value.pageNum === 1) {
          chatListData.value = resDataList.map((item, index) => {
            const { id, chatTitle, agentId } = item;
            return {
              id,
              chatTitle,
              lastMessage: '',
              agentId,
              icon: chatIconList[index % chatIconList.length]
            };
          });
        } else {
          const newData = resDataList.map((item, index) => {
            const { id, chatTitle, agentId } = item;
            return {
              id,
              chatTitle,
              lastMessage: '',
              agentId,
              icon: chatIconList[(chatListData.value.length + index) % chatIconList.length]
            };
          });
          chatListData.value = [...chatListData.value, ...newData];
        }

        pageInfo.value.total = res.total || 0;

        // 判断是否还有更多数据
        if (chatListData.value.length >= pageInfo.value.total) {
          noMoreData.value = true;
          // if (pageInfo.value.pageNum > 1) {
          //   uni.showToast({ title: '没有更多数据了' });
          // }
        } else {
          noMoreData.value = false;
        }
      })
      .catch(err => {})
      .finally(() => {
        showLoading && cancelLoading();
        loadingMore.value = false;
      });
  };

  onShow(() => {
    pageInfo.value.pageNum = 1;
    hasTriedLoadMore.value = false; 
    getChatList();
  });

  // 加载更多
  const loadMore = () => {
    if (loadingMore.value || noMoreData.value) return;
    loadingMore.value = true;
    hasTriedLoadMore.value = true; 
    pageInfo.value.pageNum++;
    getChatList(false);
  };

  const swipeOptions = ref([
    {
      text: '删除',
      style: {
        backgroundColor: '#FF2B2B',
        fontSize: '16px'
      }
    }
  ]);

  const handleSwipeClick = (e, item) => {
    if (e.index === 0) {
      uni.showModal({
        title: '确认删除',
        content: `确定删除与对话【${item.chatTitle}】吗？`,
        success: res => {
          if (res.confirm) {
            delChatApi(item.id)
              .then(res => {
                getChatList(false);
                uni.showToast({ title: '删除成功' });
              })
              .catch(err => {});
          }
        }
      });
    }
  };

  const handleClick = (item = undefined) => {
    if (item) {
      const { id, agentId, chatTitle } = item;
      uni.navigateTo({
        url: `/pages/chat/index?chatId=${id}&agentId=${agentId}&chatTitle=${chatTitle}`
      });
    } else {
      uni.navigateTo({
        url: `/pages/chat/index?agentId=${chatStore.agentId}`
      });
    }
  };

  const handleMore = () => {
    handleClick();
  };
</script>

<style lang="scss" scoped>
  .chatList-page {
    padding: 0rpx 14rpx 0rpx 14rpx;
    padding-top: var(--status-bar-height);
    .chatList-page-content {
      height: calc(100vh - var(--status-bar-height));
      // #ifdef H5
      height: calc(100vh - var(--status-bar-height) - 50px);
      // #endif
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }
  }

  :deep(.custom-nav-bar) {
    flex: none;
    height: 44px !important;
    min-height: unset !important;
    .uni-navbar__content {
      background-color: transparent !important;
      .uni-navbar__header {
        background-color: transparent !important;
      }
    }
    .nav-bar-add-btn-icon {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .search-container {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .search-input {
      flex: 1;
    }

    .search-btn {
      flex: none;
      margin-right: 10px;
    }
  }

  .chat-list-main {
    height: calc(100vh - 60px);
    overflow: hidden;

    .custom-thumb {
      width: 28px;
      height: 28px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      flex: none;

      .thumb-image {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    :deep(.custom-list) {
      .uni-list--border:after {
        height: 0px !important;
      }
    }

    .custom-list-empty {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .main-enter {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        .enterFrom-img {
          width: 104rpx * 2;
          height: 104rpx * 2;
          margin-bottom: 14rpx * 2;
        }

        .button-text {
          line-height: 1.1;
          text-align: center;
        }
      }
    }

    .load-more,
    .no-more {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20rpx 0;
      color: #999;
      font-size: 28rpx;
    }

    ::v-deep .uni-list-item__container {
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      padding-left: 12px;
      border-bottom: 2rpx solid #e7e7e7;

      .uni-list-item__content-title {
        font-weight: bold;
      }

      .uni-list-item__content-title,
      .uni-list-item__content-note {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: block;
      }
    }
  }
</style>
